import { Eventable } from "./Eventable.js";

export class Timer extends Eventable {
    #interval: number;
    #timer: number = 0;

    constructor(interval: number) {
        super();
        this.#interval = interval;
    }

    get interval(): number {
        return this.#interval;
    }

    set interval(value: number) {
        if (value === this.#interval) {
            return;
        }

        this.#interval = value;
        this.restart();
    }

    restart(): void {
        this.stop();
        this.#timer = setInterval(this.process.bind(this), this.#interval);
    }

    stop(): void {
        clearInterval(this.#timer);
    }

    private process(): void {
        this.trigger("performed");
    }
}
